<?php

namespace Wechat\Controller;

use Common\Lib\Upload\ImgManager;

class AjaxController extends CommonController
{
    // ajax用户登录检测
    public function ajax_login()
    {
        if (D('User')->is_login()) {
            $this->ajaxReturn(2, '');
        } else {
            $openid = session('ytatatmp.openid');
            $userinfo = D('User')->get_user_one($openid, false, 4);
            if (!empty($userinfo)) {
                D('User')->user_login($userinfo);
                $this->ajaxReturn(2, '');
            } else {
                // 用户注册时是否强制认证手机号，1为认证手机号
                $wvm = C('YTATA_WEIXIN_VERIFY_MOBILE');
                if (empty($wvm)) {
                    $ret = D('User')->user_reg('', '', $openid, '', true);
                    if ($ret['status'] == '1') {
                        $this->ajaxReturn(2, '');
                    }
                }
            }
        }
        $act = I('param.act', '', 'trim');
        $params = I('param.params', '', 'trim');
        $this->assign(compact('act', 'params'));
        $html = $this->fetch();
        $this->ajaxReturn(1, '', $html);
    }

    // 发送验证码
    public function ajax_send_mobile_code()
    {
        $mobile_post = I('request.mobile', '', 'trim');
        if (!preg_match("/^1[23456789]{1}\d{9}$/", $mobile_post)) {
            $this->ajaxReturn(0, "手机号{" . $mobile_post . "}格式错误！");
        } else {
            $mobile_code = strval(rand(1000, 9999));
            $params = array('rand' => $mobile_code);
            $send = send_sms($mobile_post, $params, 'mobile_code');
            if ($send['status'] == '0') {
                $this->ajaxReturn(0, $send['content']);
            }
            session('mobile_code', $mobile_code);
            session('mobile_post', $mobile_post);
            session('code_err_is3', null);
            $this->ajaxReturn(1, "验证码发送成功！");
        }
    }

    /**
     * 验证验证码是否正确，正确并注册成功返回成功，否则返回失败
     * 如果手机号已注册，则绑定微信openid
     * 如果手机号未注册，使用手机和openid进行注册
     */
    public function ajax_verify_mobile_code()
    {
        $code = I('post.code', '', 'trim');
        $mobile = I('post.mobile');
        $mobile_code = session('mobile_code');
        $mobile_post = session('mobile_post');

        if (empty($mobile_code)) {
            $this->ajaxReturn(0, '请先获取验证码');
        }

        if (empty($mobile) || $mobile <> $mobile_post) {
            $this->ajaxReturn(0, '手机号填写错误');
        }

        if (empty($code) || $code <> $mobile_code) {
            $code_err = session('code_err');
            $code_err_is3 = session('code_err_is3');
            $code_err = intval($code_err) + 1;
            if ($code_err > 3 || $code_err_is3) {
                session('code_err', null);
                session('code_err_is3', 'true');
                session('mobile_code', null);
                $this->ajaxReturn(0, '验证码连续3次出错，请重新发送！');
            }
            session('code_err', $code_err);
            $this->ajaxReturn(0, '验证码错误，请重新输入');
        }

        $user = D('User')->get_user_one($mobile, false, 2);
        if ($user) {
            //只有手机号，没有OPENID时，加上openid用于下次直接登录（只有手机的账号一般来自PC端）
            D('User')->update_user_openid($user['uid'], session('ytatatmp.openid'));
            D('User')->user_login($user);
            if (D('User')->is_login()) {
                $this->ajaxReturn(1, '已登录');
            } else {
                $this->ajaxReturn(0, '登录失败');
            }
        } else {
            $ret = D('User')->user_reg('', $mobile, session('ytatatmp.openid'), '', true);
            $this->ajaxReturn($ret['status'], $ret['content']);
        }
    }

    // 获取分类列表
    public function ajax_category()
    {
        $type = I('request.type', 1, 'intval');
        $pid = I('request.pid', 0, 'intval');
        $selectid1 = I('request.selectid1', 0, 'intval');//已选的大类
        $selectid2 = I('request.selectid2', 0, 'intval');//已选的小类
        $selectids = "{$selectid1},{$selectid2}";//已选的分类字符（大类+小类）用户恢复选择状态
        $cat_level = intval(C('YTATA_CAT_LEVEL_QUESTION', null, 1));
        $this->assign('cat_level', $cat_level);
        $this->assign('pid', $pid);
        $this->assign('type', $type);
        $this->assign('selectids', $selectids);
        $html = $this->fetch();
        $this->ajaxReturn(1, '', $html);
    }

    // 获取问题排序方式
    public function ajax_question_sort()
    {
        $html = $this->fetch();

        $this->ajaxReturn(1, '', $html);
    }

    // 获取文章排序方式
    public function ajax_article_sort()
    {
        $html = $this->fetch();

        $this->ajaxReturn(1, '', $html);
    }

    // 获取论坛主题排序方式
    public function ajax_bbs_sort()
    {
        $html = $this->fetch();

        $this->ajaxReturn(1, '', $html);
    }

    // 打开通用菜单
    public function ajax_sliding_nav()
    {
        $openid = session('ytatatmp.openid');
        $userinfo = D('User')->get_user_one($openid, true, 4);
        if (empty($userinfo)) {
            $userinfo['nickname'] = session('ytatatmp.nickname');
            $userinfo['avatar'] = session('ytatatmp.headimgurl');
            $userinfo['openid'] = $openid;
            $userinfo['exp'] = 0;
            $userinfo['exp_lv'] = 1;
            $userinfo['mobile'] = '';
        }
        //dump($userinfo);
        $lv = D('Lv')->get_lv_one($userinfo['exp_lv']);
        $userinfo['percentage'] = D('User')->get_exp_percentage($userinfo['exp'], $lv['exp_max']);
        if (empty($userinfo['percentage'])) {
            $userinfo['percentage'] = '20%';
        }
        $this->assign('lv', $lv);
        $this->assign('userinfo', $userinfo);
        $html = $this->fetch();
        $this->ajaxReturn(1, '', $html);
    }

    // 上传图片
    public function ajax_upload_img()
    {
        $pic = base64_decode($_POST['base64_string']);

        $savepath = C('YTATA_IMG_QUESTION_DIR') . date('Y/m/');
        if (!is_dir($savepath)) {
            mkdir($savepath, 0777, true);
        }
        $savename = md5(time()) . '.jpg';
        $filename = $savepath . $savename;
        file_put_contents($filename, $pic);

        $image = new \Common\ORG\ThinkImage();
        $path = $filename;
        $imageModel = $image->open($path);
        $thumb_width = $imageModel->width();
        $thumb_height = $imageModel->height();
        $imageModel->thumb($thumb_width, $thumb_height)->save($path);

        $imageModel = $image->open($path);
        $thumb_width = 100;
        $thumb_height = 100;
        $imageModel->thumb($thumb_width, $thumb_height)->save($path . '.thumb.jpg');

        $img = D('UploadImg')->get_one_file($filename);
        if (empty($img)) {
            $data['sha1'] = sha1_file($filename);
            $data['name'] = $savename;
            $data['savename'] = $savename;
            $data['savepath'] = $savepath;
            $data['savetype'] = 'local';
            $data['type'] = 'image/jpeg';
            $data['ext'] = 'jpg';
            $data['size'] = filesize($filename);
            $img = D('UploadImg')->register($data);
        } else {
            unlink($filename);
            unlink($path . '.thumb.jpg');
        }

        $ret['id'] = $img['id'];
        $img_manager = new ImgManager($img);
        $ret['src'] = $img_manager->url();

        $this->ajaxReturn(1, '上传头像成功', $ret);
    }

    // 违规内容举报 [包括提问/回复等]
    public function ajax_report()
    {
        $html = $this->fetch();
        $this->ajaxReturn(1, '', $html);
    }

    // 违规内容举报保存 [包括提问/回复等]
    public function ajax_report_save()
    {
        $this->check_login();
        $content = I('request.content', '', 'trim');
        $objid = I('request.objid');
        $type = I('request.type');
        $ret = D('Report')->report_add($content, $objid, $type);
        return $this->ajaxReturn($ret['status'], $ret['msg'], $ret['newid']);
    }

    // 点赞
    public function ajax_praise()
    {
        $this->check_login();
        $uid = session('ytata.uid');
        $objid = I('param.id', '', 'intval');
        $type = I('param.type', '', 'intval');

        switch ($type) {
            case 1:
                $ret = D('Question')->praise($uid, $objid);
                break;
            case 2:
                $ret = D('Answer')->praise($uid, $objid);
                break;
            case 3:
                $ret = D('Bbs')->praise($uid, $objid);
                break;
            case 4:
                $ret = D('BbsReply')->praise($uid, $objid);
                break;
            case 5:
                $ret = D('Article')->praise($uid, $objid);
                break;
            default:
                $this->ajaxReturn(0, '参数错误');
                break;
        }

        if ($ret['status'] == 2) {
            $this->ajaxReturn(2, $ret['msg']);
        } elseif ($ret['status'] == 1) {
            $data['id'] = $objid;
            $data['count_str'] = format_praise($ret['count_praise']);
            if ($type == 5) {
                $data['count_str'] = '赞：' . $data['count_str'];
            }
            $this->ajaxReturn(1, $ret['msg'], $data);
        } else {
            $this->ajaxReturn(0, $ret['msg']);
        }
    }

    // 关注
    public function ajax_follow()
    {
        $this->check_login();
        $uid = session('ytata.uid');
        $type = I('param.type', '', 'intval');  // 1-问题
        $objid = I('param.objid', '', 'intval');

        switch ($type) {
            case 1:
                $ret = D('Question')->follow($objid, $uid);
                break;
            case 2:
                $ret = D('Bbs')->follow($objid, $uid);
                break;
            default:
                $this->ajaxReturn(0, '参数错误');
                break;
        }
        if ($ret['status'] == 2) {
            $this->ajaxReturn(2, '已取消关注');
        } elseif ($ret['status'] == 1) {
            $this->ajaxReturn(1, '关注成功');
        } else {
            $this->ajaxReturn(0, '关注失败');
        }
    }

    // 收藏问题
    public function ajax_favorites()
    {
        $this->check_login();
        $uid = session('ytata.uid');
        $id = I('param.id', '', 'intval');
        $type = I('param.type', '', 'intval');

        if (empty($id)) {
            $this->ajaxReturn(0, '参数错误');
        }

        if (D('UserFavorites')->chenk_favorites($uid, $id, $type)) {
            $this->ajaxReturn(2, '已经收藏过了');
        } else {
            D('UserFavorites')->add_favorites($uid, $id, $type);

            $this->ajaxReturn(1, '收藏成功', compact('id', 'type'));
        }
    }
}

?>